from target.indicator_ma import *

import talib
import numpy as np

 #用户代码init
def init(self):
    # 需要设置计算MACD的相关参数参数
    self.short = 12
    self.long = 26
    self.smoothperiod = 9
    self.observation = 100
    

#用户策略代码
def on_bar(self):
    if self.order:
        return
    self.cash = self.get_cash()   #获取现金
    self.dataclose = self.datas[0].close  #获取价格
    self.dates = self.datas[0].datetime.date(0).isoformat()  #当前日

    self.priceArr = self.optainData(data = self.datas[0].close,ago = 0,size = self.observation)
    if len(self.priceArr) < 100:
        return
    else: 

        macd, signal, hist = talib.MACD(self.priceArr, self.short,
                                self.long, self.smoothperiod)

        # 策略逻辑
        # 卖出逻辑 macd下穿signal
        if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0:
            # 有持仓进行清仓
            if self.position:
                self.open_close()
        # 买入逻辑  macd上穿signal
        if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0:
            # 空仓买入股票
            if not self.position:
                self.open_buy(size=100)